<?php
namespace App\Api\Controllers\Hltx;


use App\Common\Log;
use App\Common\PaySuccessAction;
use App\Models\HltxCofig;
use App\Models\HltxStore;
use App\Models\Order;
use App\Models\Store;
use App\Models\StorePayWay;
use App\Models\UserRate;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;

class ManageController extends BaseController
{

    public function pay_config($config_id, $qd = 1)
    {
        //配置取缓存
        $config = HltxCofig::where('config_id', $config_id)
            ->where('qd', $qd)
            ->first();
        if (!$config) {
            $config = HltxCofig::where('config_id', '1234')
                ->where('qd', $qd)
                ->first();
        }

        return $config;
    }


    public function pay_merchant($store_id, $store_pid)
    {
        if ($store_pid) {
            //分店配置
            $merchant = HltxStore::where('store_id', $store_id)->first();
            if (!$merchant) {
                $store_pid_id = '';
                $store_p = Store::where('id', $store_pid)
                    ->select('store_id')
                    ->first();

                if ($store_p) {
                    $store_pid_id = $store_p->store_id;
                }

                $merchant = HltxStore::where('store_id', $store_pid_id)->first();
            }


        } else {
            $merchant = HltxStore::where('store_id', $store_id)->first();
        }

        return $merchant;
    }


    public function edit_store_rate(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id');
            $ways_type = $request->get('ways_type');
            $rate = $request->get('rate');//单一费率
            $rate_b = $request->get('rate_b');//借记卡一档
            $rate_d = $request->get('rate_d');//借记卡二档
            $rate_b_top = $request->get('rate_b_top', '20');//借记卡封顶
            $rate_a = $request->get('rate_a');//贷记卡一档
            $rate_c = $request->get('rate_c');//贷记卡二档
            $store = Store::where('store_id', $store_id)
                ->first();

            if (!$store) {
                return json_encode(['status' => 2, 'message' => '门店不存在', 'data' => []]);
            }

            //共享通道不支持修改费率
            if ($store->pay_ways_type) {
                return json_encode(['status' => 2, 'message' => '共享通道不支持修改费率']);
            }


            //代理商的费率
            $user_rate = UserRate::where('user_id', $store->user_id)
                ->where('ways_type', $ways_type)
                ->select('rate_a', 'rate_b')
                ->first();


            if (!$user_rate) {
                return json_encode(['status' => 2, 'message' => '代理商未设置费率', 'data' => []]);
            }
            //不能低于代理商的成本
            if ($rate < $user_rate->rate) {
                return json_encode(['status' => 2, 'message' => '单一费率费率不能低于代理商的费率', 'data' => []]);
            }
            //不能大于代理商的成本
            if ($rate_a < $user_rate->rate_a) {
                return json_encode(['status' => 2, 'message' => '小于1000贷记卡费率不能低于代理商的费率', 'data' => []]);
            }
            //不能大于代理商的成本
            if ($rate_b < $user_rate->rate_b) {
                return json_encode(['status' => 2, 'message' => '小于1000费率不能低于代理商的费率', 'data' => []]);
            }


            //不能大于代理商的成本
            if ($rate_c < $user_rate->rate_c) {
                return json_encode(['status' => 2, 'message' => '大于1000贷记卡费率不能低于代理商的费率', 'data' => []]);
            }
            //不能大于代理商的成本
            if ($rate_d < $user_rate->rate_d) {
                return json_encode(['status' => 2, 'message' => '大于1000借记卡费率不能低于代理商的费率', 'data' => []]);
            }

            $ways = StorePayWay::where('store_id', $store_id)->where('ways_type', $ways_type)
                ->first();

            if (!$ways) {
                return json_encode(['status' => 2, 'message' => '请先设置扫码通道', 'data' => []]);
            } else {
                $status = $ways->status;
                $status_desc = $ways->status_desc;

                //如果通道审核中不允许修改费率
                if ($status == 4) {
                    return json_encode(['status' => 2, 'message' => '通道审核中不允许修改费率', 'data' => []]);
                }
                if ($status == 3) {
                    return json_encode(['status' => 2, 'message' => '进件失败不允许修改费率', 'data' => []]);
                }
                $HltxStore = HltxStore::where('store_id', $store_id)->first();
                if ($HltxStore && !empty($HltxStore->mer_no)) {
                    //允许修改费率
                    $hltx_config = $this->pay_config($store->config_id);
                    $this->init($hltx_config);//初始化配置
                    $return = $this->hltx_edit_payinfo_merchant($HltxStore->mer_no, $rate, $rate_b, $rate_d, $rate_b_top, $rate_a, $rate_c);
                    if ($return['status'] != 1) {
                        return json_encode(['status' => 2, 'message' => '费率修改失败:' . $return['message'], 'data' => []]);
                    }
                    $return = $return['data'];
                    if ($return['status'] == '00') {
                        //成功
                    } else {
                        return json_encode(['status' => 2, 'message' => '请求申请修改用户通道费率业务失败', 'data' => []]);
                    }
                } else {
                    return json_encode(['status' => 2, 'message' => '通道未成功开通不允许修改费率', 'data' => []]);
                }
            }

            $company = $ways->company;

            //全部设置
            $update_data = [
                'rate_a' => $rate_a,
                'rate_b' => $rate_b,
                'rate_b_top' => $rate_b_top,
                'rate_c' => $rate_c,
                'rate_d' => $rate_d,
                'rate' => $rate,
            ];
            StorePayWay::where('store_id', $store_id)
                ->where('company', $company)
                ->update($update_data);


            return json_encode(['status' => 1, 'message' => '设置成功', 'data' => []]);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }
    }


    public function weixin_config_set(Request $request)
    {
        try {
            $user = $this->parseToken();
            $store_id = $request->get('store_id');
            $ways_type = $request->get('ways_type');
            $hltx_sub_scribe_appid = $request->get('hltx_sub_scribe_appid');//子商户推荐关注公众号
            $hltx_wx_path = $request->get('hltx_wx_path');//支付目录
            $hltx_wx_path = $hltx_wx_path ?: url('api/hltx/weixin/') . '/';
            //检测必要参数
            $data = [
                'hltx_sub_scribe_appid' => $hltx_sub_scribe_appid,
            ];
            $check_data = [
                'hltx_sub_scribe_appid' => '推荐关注公众号appid',
            ];

            $check = $this->check_required($data, $check_data);
            if ($check) {
                return json_encode([
                    'status' => 2,
                    'message' => $check
                ]);
            }
            $store = Store::where('store_id', $store_id)
                ->first();

            if (!$store) {
                return json_encode(['status' => 2, 'message' => '门店不存在', 'data' => []]);
            }
            $hltx_config = $this->pay_config($store->config_id);
            if (!$hltx_config) {
                return json_encode(['status' => 2, 'message' => 'HL通道配置不存在']);
            }
            $HltxStore = HltxStore::where('store_id', $store_id)->first();
            if (!$HltxStore) {
                return json_encode(['status' => 2, 'message' => 'HL通道不存在']);
            }
            //
            if (empty($HltxStore->mer_no)) {
                return json_encode(['status' => 2, 'message' => 'HL通道未开通不允许设置']);
            }
            if (!empty($HltxStore->mer_no) && empty($HltxStore->wx_merchant_no)) {
                return json_encode(['status' => 2, 'message' => 'HL通道微信未成功开停工不允许设置']);
            } else {
                $this->init($hltx_config);
                $params = [
                    'merNo' => $HltxStore->mer_no,
                    'path' => $hltx_wx_path,
                    'appId' => $hltx_config->pay_appid,
                    'subScribeAppIds' => $hltx_sub_scribe_appid,
//                    'channelId'=>$hltx_config->wx_channelid,
//                    'paymentPrdNo'=>'WX',
                ];
                $return = $this->merchant_wxsetconig($params);
                if ($return['status'] == 1) {
                    $return = $return['data'];
                    if ($return['code'] == '0000') {
                        if ($return['type'] == "S") {
                            $HltxStore->update(['sub_scribe_appid' => $hltx_sub_scribe_appid]);
                            $HltxStore->save();
                        } else {
                            return json_encode(['status' => 2, 'message' => '请求业务失败:' . $return['message']]);
                        }
                    } else {
                        return json_encode(['status' => 2, 'message' => $return['message']]);
                    }
                } else {
                    return json_encode(['status' => 2, 'message' => $return['message']]);
                }
            }
            return json_encode(['status' => 1, 'message' => '设置成功', 'data' => []]);


        } catch (\Exception $exception) {
            return json_encode(['status' => -1, 'message' => $exception->getMessage() . ' - ' . $exception->getLine()]);
        }
    }


    public function pay_notify(Request $request)
    {
        try {
            $data = $request->all();
            if ($data && isset($data['signature'])) {
                $day = date('Ymd', time());
                $table = 'orders_' . $day;
                if (Schema::hasTable($table)) {
                    $order = DB::table($table)->where('out_trade_no', $data['orderNo'])->first();

                } else {
                    $order = Order::where('out_trade_no', $data['orderNo'])->first();
                }

                if (!$order) {
                    return '';
                }
                $config_id = $order->config_id;//平台秘钥验签
                $hltx_config = $this->pay_config($config_id);
                if (!$hltx_config) {
                    $hltx_config = HltxStore::where('config_id', '1234')->first();
                }
                $this->init($hltx_config);
                if ($this->signVerify($data)) {
                    if ($data['tradeStatus'] != $order->status) {
                        if ($order->pay_status != 1) {
                            $update_data = [
                                'status' => 'S',
                                'pay_status' => 1,
                                'pay_status_desc' => '支付成功',
                                'trade_no' => $data['transIndex'],
                                'pay_time' => $data['payCompleteTime'],
                                'buyer_pay_amount' => $data['amount'] / 100
                            ];


                            $this->update_day_order($update_data, $data['orderNo']);

                            if (strpos($order->out_trade_no, 'scan')) {

                            } else {
                                //支付成功后的动作
                                $data = [
                                    'ways_type' => $order->ways_type,
                                    'ways_type_desc' => $order->ways_type_desc,
                                    'source_type' => '23000',//返佣来源
                                    'source_desc' => 'HL',//返佣来源说明
                                    'total_amount' => $order->total_amount,
                                    'out_trade_no' => $order->out_trade_no,
                                    'other_no' => $order->other_no,
                                    'rate' => $order->rate,
                                    'company' => $order->company,
                                    'fee_amount' => $order->fee_amount,
                                    'merchant_id' => $order->merchant_id,
                                    'store_id' => $order->store_id,
                                    'user_id' => $order->user_id,
                                    'config_id' => $order->config_id,
                                    'store_name' => $order->store_name,
                                    'ways_source' => $order->ways_source,
                                    'pay_time' => $data['payCompleteTime'],
                                    'device_id' => $order->device_id,
                                ];
                                PaySuccessAction::action($data);
                            }
                        }
                    }

                    return json_encode(['code' => '0000']);
                }
            }
        } catch (\Exception $e) {
            Log::write($e->getMessage() . $e->getLine(), 'hltx_qr_err.log');
        }
        return 'FAIL';
    }


    /**
     * 预下单
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function pay($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'orderNo' => $data['orderNo'] . '',
                'tradeType' => $data['tradeType'] . '',
                'subTradeType' => $data['subTradeType'] . '',
                'amount' => $data['amount'] . '',
                'orderInfo' => $data['orderInfo'] . '',
                'notifyUrl' => $data['notifyUrl'] . '',
                'deviceNo' => $data['deviceNo'] . '',
                'deviceIp' => $data['deviceIp'] . '',
            ];
            if (in_array($data['tradeType'], ['WX', "ALI", "UPAY"]) && $data['subTradeType'] == 'JSAPI') {
                if ($data['tradeType'] == "WX") {
                    $params['extParams'] = json_encode(['subAppId' => $data['subAppId'], 'subOpenId' => $data['userId']], JSON_UNESCAPED_UNICODE);
                } else {
                    $params['extParams'] = json_encode(['userId' => $data['userId']], JSON_UNESCAPED_UNICODE);
                }
            }
            $result = $this->public_request($reqMsgId, $params, $this->prepay_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 刷卡支付
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function scan_pay($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'orderNo' => $data['orderNo'] . '',
                'amount' => $data['amount'] . '',
                'paymentCode' => $data['paymentCode'] . '',
                'orderInfo' => $data['orderInfo'] . '',
                'deviceNo' => $data['deviceNo'] . '',
                'deviceIp' => $data['deviceIp'] . '',
            ];
            if (isset($data['tradeType']) && in_array($data['tradeType'], ['WX', "ALI", "UPAY"])) {
                $params['tradeType'] = $data['tradeType'];
            }
            $result = $this->public_request($reqMsgId, $params, $this->scanpay_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 撤销订单
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function cancel_order($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'oriOrderNo' => $data['orderNo'] . '',
            ];
            $result = $this->public_request($reqMsgId, $params, $this->cancel_order_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 预下单关闭订单
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function close_order($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'oriOrderNo' => $data['orderNo'] . '',
            ];
            $result = $this->public_request($reqMsgId, $params, $this->close_order_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 订单退款
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function refund_order($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'amount' => $data['amount'] . '',
                'orderNo' => $data['orderNo'] . '',
                'oriOrderNo' => $data['oriOrderNo'] . '',
                'orderInfo' => $data['orderInfo'] . '',
                'deviceIp' => $data['deviceIp'] . '',
            ];
            if (isset($data['transIndex'])) {
                $params['transIndex'] = $data['transIndex'];
            }
            if (isset($data['deviceNo'])) {
                $params['deviceNo'] = $data['deviceNo'];
            }
            if (isset($data['reqReserved'])) {
                $params['reqReserved'] = $data['reqReserved'];
            }
            $result = $this->public_request($reqMsgId, $params, $this->refund_order_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 订单查询
     * @param $data
     * @param string $reqMsgId
     * @return array
     */
    public function query_order($data, $reqMsgId = '')
    {
        try {
            $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
            $params = [
                'merNo' => $data['merNo'] . '',
                'orderNo' => $data['orderNo'] . '',
            ];
            $result = $this->public_request($reqMsgId, $params, $this->query_order_url);
            return $result;
        } catch (\Exception $e) {
            return ['status' => 2, 'message' => '支付异常:' . $e->getMessage() . $e->getLine()];
        }
    }


    /**
     * 初始化参数
     * @param $hltx_config
     */
    public function init($hltx_config)
    {
        $this->isvId = $hltx_config->isvid;
        $this->public_key = $hltx_config->public_key;
        $this->private_key = $hltx_config->private_key;
        $this->ali_pid = $hltx_config->ali_pid;
        $this->wx_channelid = $hltx_config->wx_channelid;
        $this->subscribe_appid = $hltx_config->subscribe_appid;
        $this->wx_appid = $hltx_config->wx_appid;
        $this->wx_secret = $hltx_config->wx_secret;
        $this->merchant_notify_url = url('api/hltx/merchant_notify');
    }


    /**
     * 入驻结果查询
     * @param $serialNo
     * @return array
     */
    public function hltx_merchant_result_query($serialNo)
    {
        $reqMsgId = $this->getReqMsgId();//请求单号
        $params = [
            'serialNo' => $serialNo,
        ];
//        00 入驻成功（审核通过并且所有通道报备
//        成功）
//        01 入驻失败（审核驳回或全部报备失败）
//        02 已提交基本信息（审核通过待报备）
//        03 报备中（审核通过报备部分成功）
//        04 入驻审核中（审核工单审核中）
//        05 工单待提交
        $result = $this->public_request($reqMsgId, $params, $this->merchant_admission_result_query_url);
        return $result;
    }


    /**
     * 商户信息基本查询
     * @param $merNo
     * @return array
     */
    public function hltx_merchant_query($merNo)
    {
        $reqMsgId = $this->getReqMsgId();//请求单号
        $params = [
            'merNo' => $merNo,
        ];
        $result = $this->public_request($reqMsgId, $params, $this->merchant_query_url);
        return $result;
    }


    /**
     * 商户入驻
     * @param $reqMsgId
     * @param $Store
     * @param $MyBankCategory
     * @param $StoreBank
     * @param $pic
     * @return array|mixed
     */
    public function hltx_add_merchant($Store, $MyBankCategory, $StoreBank, $pic, $rate, $UserRate, $reqMsgId = '')
    {
        $reqMsgId = $reqMsgId ?: $this->getReqMsgId();//请求单号
        $bank_code = $StoreBank->bank_no . '';//开户行联行号

//        $line=DB::table('line_number')->where('INST_OUT_CODE',$bank_code)->first();
//        if($line){
//            $bank_code=$line->DIRECT_BANK_CODE;//直属银行
//        }

        $line = DB::table('bank_info')->where('bankName', $StoreBank->bank_name)->first();
        if ($line) {
            $bank_code = $line->instOutCode;//直属银行
        }

        $channelList =
            [
                'channelId' => 'DEFAULT',
                'settleType' => 'D1',
                'acctType' => $StoreBank->store_bank_type . '',
                'account' => $StoreBank->store_bank_no . '',
                'acctName' => $StoreBank->store_bank_name . '',
                'pbcBankId' => $StoreBank->bank_no . '',
                'bankReserveMobile' => (!empty($StoreBank->store_bank_phone) ? $StoreBank->store_bank_phone : $Store->people_phone) . '',
                'prdList' => [
                    [
                        'paymentPrdNo' => 'WX',
                        'feeType' => '01',
                        'feeTemplate' => $rate . '',
                        'partnerId' => $this->wx_channelid,
                    ],
                    [
                        'paymentPrdNo' => 'ALI',
                        'feeType' => '01',
                        'feeTemplate' => $rate . '',
                        'partnerId' => $this->ali_pid,
                    ],
                    [
                        'paymentPrdNo' => 'UPAY',
                        'feeType' => '02',
                        'feeTemplate' => [
                            'feeRateDebitL1' => '0.6',//
                            'feeRateDebitL2' => $rate,//银联手续费率-第二档 1000以下
                            'feeRateDebitCapL1' => '20.00',//银联手续费率-借记封顶-第一档（单位元）
                            'feeRateCreditL1' => '0.6',//银联手续费率-贷记-第一档
                            'feeRateCreditL2' => $rate,//银联手续费率-贷记-第二档
                        ],
                    ]
                ],
                'bankName' => $StoreBank->bank_name . '',
                'bankCode' => $bank_code . '',
                'branchName' => $StoreBank->sub_bank_name . '',
                'branchProvince' => $StoreBank->bank_province_code . '',
                'branchCity' => $StoreBank->bank_city_code . '',
            ];
        if (in_array($Store->store_type, [1, 2]) && $StoreBank->store_bank_type == '01') {
            $channelList['isLegalNameAcct'] = (($Store->head_name && $StoreBank->store_bank_name && $Store->head_name != $StoreBank->store_bank_name) ? '0' : '1');
        }
        $picList = [];
        foreach ($pic as $k => $v) {
            $picList[] = [
                'picType' => $this->img_arr[$k],
                'picId' => $v,
            ];
        }
        $params = [
            'merType' => $this->merchant_type[$Store->store_type] . '',//经营性质 1-个体，2-企业，3-个人
            'merName' => $Store->store_short_name,//经营性质 1-个体，2-企业，3-个人
            'merFullName' => ($Store->store_type == 3 ? '商户_' . $Store->head_name : $Store['store_name']) . '',//经营性质 1-个体，2-企业，3-个人
            'mcc' => $MyBankCategory->mcc . '',
            'legalName' => $Store->head_name . '',//负责人->一般是法人
            'legalCertNo' => (!empty($Store->head_sfz_no) ? $Store->head_sfz_no : $StoreBank->bank_sfz_no) . '',
            'legalMobile' => $Store->people_phone . '',//法人手机号->取联系人的手机号
            'legalCertStartDate' => $Store->head_sfz_stime . '',
            'legalCertEndDate' => ((empty($Store->head_sfz_time) || $Store->head_sfz_time == '长期') ? "forever" : $Store->head_sfz_time) . '',
            'contactName' => $Store->people . '',//联系人
            'contactMobile' => $Store->people_phone . '',//联系人手机号
            'contactIdNo' => (!empty($Store->head_sfz_no) ? $Store->head_sfz_no : $StoreBank->bank_sfz_no) . '',//联系人系统没有身份证号,优先取法人身份证号,再取结算人身份证号
            'province' => $Store->province_code . '',
            'city' => $Store->city_code . '',
            'area' => $Store->area_code . '',
            'addr' => $Store->store_address . '',
            'picList' => json_encode($picList, JSON_UNESCAPED_UNICODE),
            'channelList' => json_encode([$channelList], JSON_UNESCAPED_UNICODE),
            'resultNotifyUrl' => $this->merchant_notify_url,
        ];
        if (in_array($Store->store_type, [1, 2])) {
            $params['businesslicenseStart'] = $Store->store_license_stime;
            $params['businesslicenseExpired'] = ((empty($Store->store_license_time) || $Store->store_license_time == '长期') ? "forever" : $Store->store_license_time) . '';
            $params['licId'] = $Store->store_license_no;
        }
        if ($StoreBank->store_bank_type == '01' && $Store->head_name && $StoreBank->store_bank_name && $Store->head_name != $StoreBank->store_bank_name) {
            //结算卡对私 法人 结算人 姓名不一致
            if (in_array($Store->store_type, [1, 2])) {
                $params['authName'] = $StoreBank->store_bank_name;//持卡人身份证姓名
                $params['authCertNo'] = $StoreBank->bank_sfz_no;//持卡人身份证号
            }
        }

        $result = $this->public_request($reqMsgId, $params, $this->merchant_admission_url);
        return $result;
    }


    /**
     * 基础信息修改
     * @param $merNo
     * @param $Store
     * @param $MyBankCategory
     * @param $StoreBank
     * @param $picList
     * @return array|mixed
     */
    public function hltx_edit_baseinfo_merchant($merNo, $Store, $MyBankCategory, $StoreBank, $picList)
    {
        $reqMsgId = $this->getReqMsgId();
        $params = [
            'merNo' => $merNo,
            'merName' => ($Store->store_type == 1 ? '商户_' . $Store->store_short_name : $Store->store_short_name) . '',//经营性质 1-个体，2-企业，3-个人
            'mcc' => $MyBankCategory->mcc . '',
            'legalName' => $Store->people . '',
            'legalCertNo' => $StoreBank->bank_sfz_no . '',
            'legalMobile' => $Store->people_phone . '',
            'legalCertStartDate' => $StoreBank->bank_sfz_stime . '',
            'legalCertEndDate' => (empty($StoreBank->bank_sfz_time) ? "forever" : $StoreBank->bank_sfz_time) . '',
            'contactName' => $Store->people . '',
            'contactMobile' => $Store->people_phone . '',
            'contactIdNo' => $StoreBank->bank_sfz_no . '',
            'province' => $Store->province_code . '',
            'city' => $Store->city_code . '',
            'area' => $Store->area_code . '',
            'addr' => $Store->store_address . '',
            'picList' => json_encode($picList, JSON_UNESCAPED_UNICODE),
        ];
        $result = $this->public_request($reqMsgId, $params, $this->merchant_edit_baseinfo_url);
        return $result;
    }


    /**
     * 修改商户费率
     * @param $merNo
     * @param $rate
     * @param $feeRateDebitL1
     * @param $feeRateDebitL2
     * @param $feeRateDebitCapL1
     * @param $feeRateCreditL1
     * @param $feeRateCreditL2
     * @return array|mixed
     */
    public function hltx_edit_payinfo_merchant($merNo, $rate, $feeRateDebitL1 = '0.6', $feeRateDebitL2 = '0.6', $feeRateDebitCapL1 = '20', $feeRateCreditL1 = '0.6', $feeRateCreditL2 = '0.6')
    {
        $reqMsgId = $this->getReqMsgId();
        $prDList = [
            [
                'paymentPrdNo' => 'WX',
                'feeType' => '01',
                'feeTemplate' => $rate . '',
                'partnerId' => $this->wx_channelid,
            ],
            [
                'paymentPrdNo' => 'ALI',
                'feeType' => '01',
                'feeTemplate' => $rate . '',
                'partnerId' => $this->ali_pid,
            ],
            [
                'paymentPrdNo' => 'UPAY',
                'feeType' => '02',
                'feeTemplate' => [
                    'feeRateDebitL1' => $feeRateDebitL1 . '',
                    'feeRateDebitL2' => $rate . '',
                    'feeRateDebitCapL1' => $feeRateDebitCapL1 . '',//银联手续费率-借记封顶-第一档（单位元）
                    'feeRateCreditL1' => $feeRateCreditL1 . '',//银联手续费率-贷记-第一档
                    'feeRateCreditL2' => $rate . '',//银联手续费率-贷记-第二档
                ],
            ]
        ];

        $params = [
            'merNo' => $merNo,
            'channelId' => 'RUIPAY-ISV-PE',
            'prdList' => json_encode($prDList, JSON_UNESCAPED_UNICODE)
        ];

        $result = $this->public_request($reqMsgId, $params, $this->merchant_edit_payinfo_url);
        return $result;
    }


    /**
     * 配置商户微信支付目录
     * @param $params
     * @return array
     */
    public function merchant_wxsetconig($params)
    {
        $reqMsgId = $this->getReqMsgId();
//        $params=[
//            'merNo'=>$merNo,
////            'path'=>$path,
//            'appId'=>$appid,
//            'subScribeAppIds'=>$subscribe_appid,
////            'channelId'=>'DEFAULT',
////            'paymentPrdNo'=>'WX',
//        ];
        $result = $this->public_request($reqMsgId, $params, $this->merchant_wxset_url);
        return $result;
    }


    public function merchant_notify(Request $request)
    {
        $data = $request->all();
        if ($data && isset($data['signature'])) {
            $req_id = $data['oriReqMsgId'];
            $hltx_store = HltxStore::where('req_id', $req_id)->first();
            if ($hltx_store) {
                $hltx_config = HltxCofig::find($hltx_store->config_id);
                if ($hltx_config) {
                    $hltx_manager = new ManageController();
                    $hltx_manager->init($hltx_config);
                    if ($hltx_manager->signVerify($data)) {
                        $fail_reason = isset($data['failReason']) ? strip_tags($data['failReason'], '') : '';
                        if ($data['status'] == '00') {
                            $data_update = [
                                'mer_no' => $data['merNo'],
                                'result_status' => $data['status'],//
                            ];
                            if (isset($data['wechatPayRecordMerchantNo'])) {
                                $data_update['wx_merchant_no'] = $data['wechatPayRecordMerchantNo'];
                            }
                            if (isset($data['aliPayRecordMerchantNo'])) {
                                $data_update['ali_merchant_no'] = $data['aliPayRecordMerchantNo'];
                            }
                            if (isset($data['unionPayRecordMerchantNo'])) {
                                $data_update['union_merchant_no'] = $data['unionPayRecordMerchantNo'];
                            }
                            $channelResultInfoList = json_decode($data['channelResultInfoList'], true);
                            $productResultInfoList = $channelResultInfoList[0]['productResultInfoList'];
                            foreach ($productResultInfoList as $v) {
                                if ($v['resultCode'] == 'S' && $v['prdStatus'] == '00') {
                                    continue;
                                } else {
                                    $fail_reason .= $v['paymentPrdNo'] . ":" . $v['msg'];
                                }
                            }
                            $data_update['fail_reason'] = $fail_reason;
                            $status_desc = "开通成功";
                            $status = 1;

                            //微信配置目录报备
                            $this->init($hltx_config);
                            $params = [
                                'merNo' => $data['merNo'],
                                'path' => env('APP_URL') . '/api/hltx/weixin/',
                                'appId' => $hltx_config->pay_appid,
                                'subScribeAppIds' => $hltx_config->subscribe_appid,

                            ];
                            $return = $this->merchant_wxsetconig($params);


                        } elseif ($data['status'] == '03') {//审核通过报备部分成功
                            $data_update = [
                                'mer_no' => $data['merNo'],
                                'result_status' => $data['status'],//
                                'fail_reason' => $fail_reason,//
                            ];
                            if (isset($data['wechatPayRecordMerchantNo'])) {
                                $data_update['wx_merchant_no'] = $data['wechatPayRecordMerchantNo'];
                            }
                            if (isset($data['aliPayRecordMerchantNo'])) {
                                $data_update['ali_merchant_no'] = $data['aliPayRecordMerchantNo'];
                            }
                            if (isset($data['unionPayRecordMerchantNo'])) {
                                $data_update['union_merchant_no'] = $data['unionPayRecordMerchantNo'];
                            }
                            $status_desc = "审核通过=>部分报备成功:" . $fail_reason;
                            $status = 1;
                        } elseif ($data['status'] == '01') {
                            //确认失败后继续进件
                            $data_update = [
                                'result_status' => $data['status'],//
                                'fail_reason' => $fail_reason,//
                            ];
                            $status_desc = "开通失败:" . $fail_reason;
                            $status = 3;
                        } else {
                            return '';
                        }
                        $hltx_store->update($data_update);
                        $hltx_store->save();
                        //send_ways_data
                        try {
                            //开启事务
                            $all_pay_ways = DB::table('store_ways_desc')->where('company', 'hltx')
                                ->get();
                            foreach ($all_pay_ways as $k => $v) {
                                $gets = StorePayWay::where('store_id', $hltx_store->store_id)
                                    ->where('ways_source', $v->ways_source)
                                    ->get();
                                $count = count($gets);
                                $ways = StorePayWay::where('store_id', $hltx_store->store_id)
                                    ->where('ways_type', $v->ways_type)
                                    ->first();
                                try {
                                    DB::beginTransaction();
                                    if ($ways) {
                                        $ways->update(
                                            [
                                                'status' => $status,
                                                'status_desc' => $status_desc,
                                            ]);
                                        $ways->save();
                                    }
                                    DB::commit();
                                } catch (\Exception $e) {
                                    Log::info('入库通道');
                                    Log::info($e);
                                    DB::rollBack();
                                    return '';
                                }
                            }
                        } catch (\Exception $e) {
                            Log::write('数据库操作异常' . $e->getMessage() . $e->getLine(), 'merchant_notify_err.log');
                            return '';
                        }
                        return json_encode(['code' => '0000']);
                    } else {
                        Log::write('商户入驻结果验签失败', 'merchant_notify_err.log');
                    }
                }
            }
        }
    }


    /**
     * 获取用户openID
     * @param $merNo
     * @param $userAuthCode
     * @param string $tradeType
     * @param string $appUpIdentifier
     * @return array
     */
    public function get_openid($merNo, $userAuthCode, $tradeType = 'UPAY', $appUpIdentifier = "UnionPay/1.0 CloudPay")
    {
        $reqMsgId = $this->getReqMsgId();//请求单号
        $params = [
            'merNo' => $merNo,
            'tradeType' => $tradeType,
            'appUpIdentifier' => $appUpIdentifier,
            'userAuthCode' => $userAuthCode
        ];
        $result = $this->public_request($reqMsgId, $params, $this->get_openid);
        return $result;
    }


}
